import { message } from "antd";

export const handleErrors = ({ graphQLErrors, networkError, form }) => {
  if (graphQLErrors) {
    graphQLErrors.forEach(
      ({ message: msg, locations, path, extensions: { code, property } }) => {
        switch (code) {
          case "BAD_USER_INPUT":
            if (property) {
              form.setFields({
                [property]: {
                  value: form.getFieldValue(property),
                  errors: [new Error(msg)]
                }
              });
            }
            break;
          case "UNAUTHENTICATED":
          case "UNAUTHORIZED":
            message.error(msg);
            break;
          default:
            console.log(
              `[GraphQL error]: Message: ${msg}, Location: ${JSON.stringify(
                locations
              )}, Path: ${JSON.stringify(path)}`
            );
            break;
        }
      }
    );
  }

  if (networkError) console.log(`[Network error]: ${networkError}`);
};
